import { ref, computed, type Ref, onBeforeMount } from 'vue'
import { defineStore } from 'pinia'
import dayjs from 'dayjs'

import cookies from '../cookies'

import type { Record } from '@/types/index'

interface StaticData {
  user: {
    name: string
    birthday: string
    birthdayObj: {
      year: number
      month: number
      day: number
    }
    age: number
  }
  now: {
    year: number
    month: number
    day: number
  }
}

export interface LifeCalender {
  isUserLogin: boolean
  staticData: StaticData
  model: Record
}

export const useLifeCalender = defineStore('lifeCalender', () => {
  /* 更新频率低的数据 */
  const staticData: Ref<StaticData> = ref({
    user: {
      name: '',
      birthday: '',
      birthdayObj: {
        year: 0,
        month: 0,
        day: 0
      },
      age: 0,
      birthday65Countdown: {
        ms: 0,
        day: 0,
        week: 0,
        month: 0,
        year: 0
      },
      birthday80Countdown: {
        ms: 0,
        day: 0,
        week: 0,
        month: 0,
        year: 0
      }
    },
    now: {
      year: 0,
      month: 0,
      day: 0
    }
  })

  // 用户登陆状态
  const isUserLogin = computed(() => {
    const { name, birthday } = staticData.value.user
    return !!name && !!birthday
  })

  onBeforeMount(() => {
    model.updateStaticData()
  })

  /* 方法集合 */
  const model = {
    setUserInfo: (obj: Object) => {
      cookies.setUserInfo(obj)
      model.updateStaticData()
    },
    updateStaticData: () => {
      const userInfo = cookies.getUserInfo()
      const birthday = userInfo?.birthday || ''
      const birthdayObj = {
        year: dayjs(birthday).year(),
        month: dayjs(birthday).month() + 1,
        day: dayjs(birthday).date()
      }
      const now = dayjs()
      if (!userInfo || !userInfo?.username || !birthday) {
        // console.log('updateStaticData失败：没有cookie数据')
        return
      }
      staticData.value = {
        user: {
          name: userInfo.username,
          birthday,
          birthdayObj,
          age: now.year() - dayjs(birthday).year()
        },
        now: {
          year: now.year(),
          month: now.month() + 1,
          day: now.date()
        }
      }
    },
    ageCountdown: (age: number) => {
      const { birthday } = staticData.value.user
      const now = dayjs()
      const date = dayjs(
        `${dayjs(birthday).year() + age}-${dayjs(birthday).month() + 1}-${dayjs(birthday).date()}`
      )
      const ms = date.valueOf() - now.valueOf()
      const dayMS = 24 * 60 * 60 * 1000
      return {
        ms,
        day: Math.floor(ms / dayMS),
        week: Math.floor(ms / (7 * dayMS)),
        month: Math.floor(ms / (30 * dayMS)),
        year: Math.floor(ms / (365 * dayMS))
      }
    }
  }

  return {
    isUserLogin,
    staticData,
    model
  }
})
